import React, { useState, useEffect } from 'react';
import { Input, Button, Tree, Row, Col, Space, Checkbox, message } from 'antd';
import { getTreeResourceList } from '@/services/menu';
import { getRoleInfo, addRole, updateRole } from '@/services/role';
import styles from './style.less';

type RoleItemProps = {
  children?: React.ReactElement;
  roleId: number;
  toFetchList: () => void;
  onClose: () => void;
};

const { TextArea } = Input;
const RoleItem: React.FC<RoleItemProps> = (props) => {
  const { roleId, onClose, toFetchList } = props;
  const [roleName, setRoleName] = useState<string>('');
  const [remark, setRemark] = useState<string>('');
  const [resourceIds, setResourceIds] = useState<React.Key[]>([]);
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [checkedKeys, setCheckedKeys] = useState<React.Key[]>([]);
  const [resourceData, setResourceData] = useState<MENU_API.Resources[]>([]);
  const [halfCheckedKeys, setHalfCheckedKeys] = useState<React.Key[]>([]);
  const [autoExpandParent, setAutoExpandParent] = useState<boolean>(true);

  const fetchRoleData = async () => {
    const rsp = await getRoleInfo({ id: roleId as number });
    if (rsp.code === 0) {
      const { role, checkList, resourceList, resourceIdList } = rsp.data;
      setRoleName(role.role_name);
      setRemark(role.remark);
      setResourceIds(resourceIdList);
      setResourceData(resourceList);
      setCheckedKeys(checkList);
    }
  };

  const fetchResourceData = async () => {
    const rsp = await getTreeResourceList({});
    if (rsp.code === 0) {
      const { resourceTree, resourceIdList } = rsp.data;
      setResourceData(resourceTree);
      setResourceIds(resourceIdList);
    }
  };

  useEffect(() => {
    if (roleId) {
      fetchRoleData();
    } else {
      fetchResourceData();
    }
  }, []);

  const toClose = () => {
    onClose();
  };

  const onExpand = (expandedKeysValue: React.Key[]) => {
    setExpandedKeys(expandedKeysValue);
    setAutoExpandParent(false);
  };

  const onCheck = (checkedKeysValue: React.Key[], e: any) => {
    setHalfCheckedKeys(e.halfCheckedKeys);
    setCheckedKeys(checkedKeysValue);
  };

  const handleRoleName = (e: any) => {
    setRoleName(e.target.value);
  };

  const handleRemark = (e: any) => {
    setRemark(e.target.value);
  };

  const handleAllExpand = (e: any) => {
    if (e.target.checked) {
      setExpandedKeys(resourceIds);
    } else {
      setExpandedKeys([]);
    }
  };

  const handleCheckAll = (e: any) => {
    if (e.target.checked) {
      setCheckedKeys(resourceIds);
    } else {
      setCheckedKeys([]);
    }
  };

  const toSubmit = async () => {
    if (!roleName.trim()) {
      message.warning('请输入角色名称');
      return;
    }
    if (checkedKeys.length === 0) {
      message.warning('请选择菜单配置');
      return;
    }
    const data = {
      role_name: roleName,
      is_default: 0,
      resourceIds: [...new Set([...checkedKeys, ...halfCheckedKeys])].join(','),
      remark,
    };
    const rsp = roleId ? await updateRole({ ...data, id: roleId }) : await addRole(data);
    if (rsp.code === 0) {
      message.success(`${roleId ? '角色修改成功' : '角色新增成功'} `);
      toClose();
      toFetchList();
    }
  };

  return (
    <div className={styles.roleItem}>
      <Row style={{ marginBottom: '15px' }}>
        <Col span={6} style={{ textAlign: 'right' }}>
          <div className={styles.label}>角色名称&nbsp;:&nbsp;&nbsp;</div>
        </Col>
        <Col span={18}>
          <Input placeholder="请输入角色名称" value={roleName} onChange={handleRoleName} />
        </Col>
      </Row>
      <Row style={{ marginBottom: '15px' }}>
        <Col span={6} style={{ textAlign: 'right' }}>
          <div>备注&nbsp;:&nbsp;&nbsp;</div>
        </Col>
        <Col span={18}>
          <TextArea
            placeholder="请输入备注"
            value={remark}
            onChange={handleRemark}
            autoSize={{ minRows: 3, maxRows: 5 }}
          />
        </Col>
      </Row>
      <Row>
        <Col span={6} style={{ textAlign: 'right' }}>
          <div className={styles.label}>菜单配置&nbsp;:&nbsp;&nbsp;</div>
        </Col>
        <Col span={18}>
          <div className={styles.treeBox}>
            <div className={styles.select}>
              <Space>
                <Checkbox onChange={handleAllExpand}>展开/折叠</Checkbox>
                <Checkbox onChange={handleCheckAll}>全选/不全选</Checkbox>
              </Space>
            </div>
            <div className={styles.tree}>
              <Tree
                checkStrictly={false}
                checkable={true}
                onExpand={onExpand}
                height={360}
                autoExpandParent={autoExpandParent}
                expandedKeys={expandedKeys}
                onCheck={onCheck}
                checkedKeys={checkedKeys}
                treeData={resourceData}
              />
            </div>
          </div>
        </Col>
      </Row>
      <div className={styles.footer}>
        <Space>
          <Button type="primary" onClick={toSubmit}>
            {roleId ? '保存' : '确定'}
          </Button>
          <Button onClick={toClose}>关闭</Button>
        </Space>
      </div>
    </div>
  );
};

export default RoleItem;
